#!/bin/sh

#
# Test the MBR creation ability of fwup
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
# Numbers don't matter for the test so long as the MBR is right
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77261)
define(ROOTFS_A_PART_OFFSET, 77324)
define(ROOTFS_A_PART_COUNT, 289044)
define(ROOTFS_B_PART_OFFSET, 366368)
define(ROOTFS_B_PART_COUNT, 289044)
define(APP_PART_OFFSET, 655412)
define(APP_PART_COUNT, 1799406)

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
    partition 1 {
        block-offset = \${ROOTFS_A_PART_OFFSET}
        block-count = \${ROOTFS_A_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 2 {
        block-offset = \${ROOTFS_B_PART_OFFSET}
        block-count = \${ROOTFS_B_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 3 {
        block-offset = \${APP_PART_OFFSET}
        block-count = \${APP_PART_COUNT}
        type = 0x83 # Linux
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
        }
}
EOF

# Create the expected by running base64 on the expected binary image.
base64_decode >$WORK/expected.img <<EOF
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQEADM8XBD8A
AADNLQEAAM8YBIPNFxYMLgEAFGkEAADNGBaDyxcoIJcFABRpBAAAyxgog80XmDQACgDudBsAVao=
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

# The firmware file is equivalent to the following dd call
cmp_bytes 512 $WORK/expected.img $IMGFILE

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
